package org.redis.cluster.redis.processor;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.redis.cluster.RedisCluster;
import org.redis.cluster.extension.ExtensionLoader;
import org.redis.cluster.processor.RedisReplyProcessor;
import org.redis.cluster.redis.transport.RedisReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class RedisReplyProcessorHelper {
	
	protected final Logger logger=LoggerFactory.getLogger(getClass());
	
	private RedisCluster redisCluster;
	private ExtensionLoader extensionLoader;
	
	private Map<Class<? extends RedisReply>,RedisReplyProcessor> replyProcessorMapping;
	
	public RedisReplyProcessorHelper(RedisCluster redisCluster) {
		this.redisCluster=redisCluster;
		this.extensionLoader=redisCluster.getExtensionLoader();
		this.replyProcessorMapping=initReplyProcessorMapping();
	}
	
	public byte[] process(RedisReply reply) {
		RedisReplyProcessor replyProcessor=getReplyProcessor(reply);
		if(replyProcessor==null) {
			if(logger.isWarnEnabled()) {
				logger.warn("响应没有被处理 - {}",reply);
			}
			
			return ArrayUtils.EMPTY_BYTE_ARRAY;
		}

		return replyProcessor.process(reply);
	}
	
	protected Map<Class<? extends RedisReply>,RedisReplyProcessor> initReplyProcessorMapping() {
		Collection<RedisReplyProcessor> processors=extensionLoader.load(RedisReplyProcessor.class);
		if(CollectionUtils.isEmpty(processors)) {
			return MapUtils.EMPTY_MAP;
		}
		
		Map<Class<? extends RedisReply>,RedisReplyProcessor> result=new HashMap<Class<? extends RedisReply>,RedisReplyProcessor>();
		for(RedisReplyProcessor processor:processors) {
			result.put(processor.getSupportClass(), processor);
		}
		
		return result;
	}
	
	protected RedisReplyProcessor getReplyProcessor(RedisReply redisReply) {
		return replyProcessorMapping.get(redisReply.getClass());
	}
	
	public void setReplyProcessorMapping(Map<Class<? extends RedisReply>, RedisReplyProcessor> replyProcessorMapping) {
		this.replyProcessorMapping = replyProcessorMapping;
	}
	public Map<Class<? extends RedisReply>, RedisReplyProcessor> getReplyProcessorMapping() {
		return replyProcessorMapping;
	}
	
}